from django.shortcuts import render, redirect,HttpResponse
from app01 import models
from django import forms
# 验证方式1：引入对模型的正则表达式
from django.core.validators import RegexValidator
# 验证方式2
from django.core.exceptions import ValidationError
# 后端代码安全标记到前端
from django.utils.safestring import mark_safe
#分页组件类
from app01.utils.pagination import Pagination

from app01.utils.bootstrap import BootStrapModelForm

from app01.utils.form import UserModelForm,PrettyModelForm,PrettyEditModelForm

from openpyxl import load_workbook

#------------------部门管理----------------------------------------------------------
def depart_list(request):
    """部门列表"""
    # 1、从数据加载数据
    # qureyset类型=>列表[对象，对象，对象……]
    queryset = models.Department.objects.all()
    page_object = Pagination(request, queryset, page_size=5)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, 'depart_list.html', context)

def depart_add(request):
    """添加部门"""
    # 1、处理请求
    if request.method == "GET":
        return render(request, 'depart_add.html')
    # 获取用户提交的POST请求（暂时不考虑title为空的情况，后面有简单方法处理）
    title = request.POST.get("title")
    # 2、保存到数据库
    models.Department.objects.create(title=title)
    # 3、重定向回到部门列表
    return redirect("/depart/list/")

def depart_delete(request):
    """删除部门"""
    # 1、获取id
    # 通过get请求得到url的参数实现删除http://127.0.0.1:8000/depart/delete/?nid=1
    nid = request.GET.get("nid")
    # 2、删除
    models.Department.objects.filter(id=nid).delete()
    # 3、重定向回到部门列表
    return redirect("/depart/list/")

def depart_edit(request, nid):
    """部门修改"""
    if request.method == "GET":
        # 根据nid，获取想要编辑的一行对象
        row_object = models.Department.objects.filter(id=nid).first()
        # print(row_object.id,row_object.title)
        return render(request, 'depart_edit.html', {"row_object": row_object})
    # 如果用户传递过来一个post请求
    # 1、获取用户提交的title
    title = request.POST.get("title")
    # 2、根据id到数据库中的数据进行更新
    # models.Department.objects.filter(id=nid).update(title=title,numbers = numbers,……)
    models.Department.objects.filter(id=nid).update(title=title)
    # 3、重定向用户列表
    return redirect("/depart/list/")

def depart_multi(request):
    """批量上传Excel文件"""
    #1、获取用户上传的文件对象
    file_object = request.FILES.get("exc")
    #print(type(file_object))
    #直接打开Excel并读取内容
    #from openpyxl import load_workbook

    #2、对象传递给openpyxl，由openpyxl读取文件的内容
    #wb = load_workbook("本地文件路径")
    wb = load_workbook(file_object)
    sheet = wb.worksheets[0]
    #cell = sheet.cell(2,2)#获取sheet的一行一列
    #print(cell.value)

    #3、循环获取每行数据并添加到数据库
    #sheet.rows()从第一行开始取
    #sheet.iter_rows(min_row=2)#从第二行开始取（排除标题）
    for row in sheet.iter_rows(min_row=2):
        # print(row)
        # (< Cell 'Sheet1'.A2 >,)
        # (< Cell 'Sheet1'.A3 >,)
        # (< Cell 'Sheet1'.A4 >,)
        text = row[0].value
        # print(text)
        # 技术部
        # 运营部
        # 策划部
        exists = models.Department.objects.filter(title=text).exists()
        if not exists:
            models.Department.objects.create(title=text)
    return redirect("/depart/list/")